package com.per.mybootall.mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.stereotype.Component;

/**
 * mqtt推送客户端
 * */
@Component
public class MqttPushClient {

/**
 * send发送==》》》
 * */
    public  void send(String content,int qos,String subTopic,String  broker,String username,String password,String clientId) {

        String pubTopic = "testtopic/1";

        MemoryPersistence persistence = new MemoryPersistence();

        try {
            MqttClient client = new MqttClient(broker, clientId, persistence);

            // MQTT 连接选项
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setUserName(username);
            connOpts.setPassword(password.toCharArray());
            // 保留会话
            connOpts.setCleanSession(true);

            // 设置回调
           //client.setCallback(new PushCallback());
            // 建立连接

            client.connect(connOpts);

            // 订阅      =============================》》》》》》》》》》》》》》用户只有在订阅对应的topic之后，推送才会把数据推送到对应的topic
            client.subscribe(subTopic);

            /**
             *      增加订阅
             *public void subscribe(String topic, int qos) throws MqttException {
             *         mqttClient.subscribe(topic,qos);
             *     }
             *
             *     取消订阅
             *       public void unsubscribe(String topic) throws MqttException {
             *         mqttClient.unsubscribe(topic);
             *     }
             * */


            // 消息发布所需参数
            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(qos);

            //消息发布==》》》
            client.publish(pubTopic, message);

            client.disconnect();

            client.close();
            //system.exit为0的时候会自动退出程序
            //System.exit(0);
        } catch (MqttException me) {
//            System.out.println("reason " + me.getReasonCode());
//            System.out.println("msg " + me.getMessage());
//            System.out.println("loc " + me.getLocalizedMessage());
//            System.out.println("cause " + me.getCause());
//            System.out.println("excep " + me);
            me.printStackTrace();
        }
    }

}
